<?php

class HasManyForm extends CComponent {
	
	public $model;
	public $relationName;
	public $activeForm;
	public $fields;
	
	public function render() {
		$body = '';
		foreach(array_keys($this->model->{$this->relationName}) as $one) {
			$removeJs = '$("#attr_'.$one.'").remove()';
			$body .= 
			"<tr id='attr_{$one}'>".$this->renderRow($one)."
				<td><input onclick='{$removeJs}' type='button' value='   删除   ' class='pn'/></td>
			</tr>";
		}
		
		$foot = 
		'<tr id="item-template">'.$this->renderRow('{attrId}')."
			<td><input type='button' value='   添加   ' class='pn pnc btn-add-item'/></td>
		</tr>";
		$className = get_class($this->model);
		$foot = str_replace($className, "_prefix_{$className}", $foot);
		
		$head = '';
		foreach($this->fields as $name=>$field) {
			$head .= '<th>'.$this->activeForm->labelEx($this->model, $name).'</th>';
		}
		$head .= '<th>操作</th>';
		
$template = <<<EOD
<table class='info mgb10' width=100% id='item-container'>
	<thead>{$head}</thead>
	<tbody id='item-container'>{$body}{$foot}</tbody>
</table>
EOD;

		echo $template;
		Yii::app()->clientScript->registerScript('hmf'.mktime(), $this->registerScript(), CClientScript::POS_END);
	}
	
	public function renderRow($attrId) {
		$rowTemplate = '';
		$model = $this->model;
		$form = $this->activeForm;
		foreach($this->fields as $name=>$field) {
			if(!$field->getIsVisible()) continue;
			$label = $model->getAttributeLabel($name);
			$attribute = str_replace('..', ".{$attrId}.", $name);
			$rowTemplate .= '<td class="vtop">'.
				$field->render($model, $attribute).'<br/>'.
				$form->error($model, $attribute).'</td>';
		}
		return $rowTemplate;
	}
	
	public function registerScript() {
$js = <<<EOD
$('.btn-add-item').click(function() {
	var e = $('#item-template').clone();
	e.find(':input').show();
	id = 'N-'+new Date().getTime();
	e.find('.btn-add-item')
		.removeClass('btn-add-item')
		.removeClass('pnc')
		.val('   删除   ')
		.attr('onclick', "$('#attr_{attrId}').remove()");
	html = '<tr id="attr_{attrId}">'+e.html()+"</tr>";
	html = html.replace(/\{attrId\}/g, id);
	html = html.replace(/_prefix_/g, '');
	$(html).insertBefore($('#item-template'));
});
$('#item-template :input').not(':button').hide();
EOD;
	
		return $js;
	}
	

}

?>